import Axios from 'axios'
import {getToken} from '@/utils/tool'
const axios = Axios.create({
  baseURL: process.env.REACT_APP_NODE_ENV === 'prod'? process.env.REACT_APP_API_PREFIX : '',
  timeout: 4000
});
axios.interceptors.request.use((config:any) => {
  console.log(config);
  // 获取token，并放入头部中用于登录校验
  const token = getToken();
  // 如果没有token，跳转登录页
  if(!token) {
    (window as any).$history.push('/login');
  }
  config.headers.accessToken = token;
  return config;
}, err => {
  return Promise.reject(err);
});

axios.interceptors.response.use((config) => {
  console.log(config);
  // code是-666说明登录过期
  if(config.status === 200 && config.data.code === -666) {
    (window as any).$history.push('/login');
  }
  if(config.status === 200) {
    return config.data;
  }
  return config;
});

const request = Axios.request;
(Axios as any).request = function(config:any) {
  return request(config).catch(err => {
    console.error(err)
  });
}

export default axios;